const Mock = require('mockjs')
const bodyParser = require('body-parser')

let user=[{
    "username":"13522506563",
    "password":"111111",
    "role":"user"
},{
    "username":"18510204378",
    "password":"666666",
    "role":"adiam"
},{
    "username":"17621856309",
    "password":"888888",
    "role":"user"
}]

let {list}=Mock.mock({
    "list|50":[{
        "name":"@cname",
        "age|18-50":1,
        "sex|1":['男','女'],
        "email":/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
        "tel":/^1[3-9]\d{9}$/ ,
        "county":"@county(true)",
        "hoppy|1":['篮球','排球','足球','乒乓球','网球'],
        "id":"@id"
    }]
})
let {sp}=Mock.mock({
    "sp|10":[{
        "title":"@ctitle(4)",
        "img":"@image(100x100,@color)",
        "price|100-1000":1,
        "word":"@cword(8,10)",
        "pl":[],
        "id":"@id"
    }]
})
module.exports = function (app) {
    app.use(bodyParser.json())
    app.get('/api/sp',(req,res)=>{
        res.send({
            code:200,
            sp
        })
    })
    app.get('/api/list',(req,res)=>{
        res.send({
            code:200,
            list
        })
    })
    app.post('/api/login',(req,res)=>{
        const {username,password}=req.body
        let item=user.find((item)=>item.username===username)
        if (item) {
            res.send({
                code:200,
                msg:"登录成功",
                token:item.username,
                role:item.role
            })
        }
    })
    app.get('/api/del',(req,res)=>{
        let {id}=req.query
        list=list.filter((item)=>item.id!==id)
        res.send({
            code:200,
            msg:"删除成功"
        })
    })
    app.post('/api/edit',(req,res)=>{
        let { id } = req.body
        const item = list.find((item) => item.id === id)
        if (item) {
            Object.assign(item, req.body)
            res.send({
                code: 200,
                msg: '修改成功',
            })
        } else {
            res.send({
                code: 400,
                msg: '修改失败',
            })
        }
    })
}
